import React from 'react';
import { Link } from 'react-router';
import ReactDOM from 'react-dom';
import Dropzone from 'react-dropzone';
import { hashHistory } from 'react-router';
require("./home.css");

 // Tab选择器组件
class TabsControl extends React.Component{
    constructor() {
        super();
        this.state={currentIndex : 0};
     }

     check_tittle_index(index){
         return index===this.state.currentIndex ? "Me_tittle Me_active" : "Me_tittle";
     }

     check_item_index(index){
         return index===this.state.currentIndex ? "Me_item Me_show" : "Me_item";
     }

     render(){
         return(
             <div>
                 <div className="Me_tittle_wrap">
                      { React.Children.map( this.props.children , (element,index) => {
                          return(
                             <div onClick={ () => { this.setState({currentIndex : index}) } } className={ this.check_tittle_index(index) }>{ element.props.name }</div>
                         );
                      }) }
                     <hr/>
                 </div>
                 <div className="Me_item_wrap">
                     {React.Children.map(this.props.children,(element,index)=>{
                         return(
                              <div className={ this.check_item_index(index) }>{ element }</div>
                         );
                     })}
                 </div>
             </div>
         );
     }
 }

 // 公司设置组件
class CompSet extends React.Component {
    constructor() {
        super();
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
        console.log(userSessionStorage);
        this.state = {
            loginID : userSessionStorage.user_id,
            companyID : userSessionStorage.company_id,
            loginImage : userSessionStorage.user_image,
            companyName : '',
            companyInfo : '',
            uploadedFile: null,
            uploadedFileCloudinaryUrl: ''
        };
    }

    // 在渲染组件之前预加载数据
    componentWillMount(){
        this.LoadData();
    }

    // 一开始就从服务端拿到公司信息
    LoadData(){
        fetch("http://121.196.202.247:1010/t_company/?user_id="+this.state.loginID, {
            method: "GET",
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json; charset=utf-8"
            }}) .then((response) => response.json())
            .then((responseText) => {
                this.setState({companyName: responseText.company_name});
                this.setState({uploadedFileCloudinaryUrl: responseText.company_img});
                this.setState({companyInfo: responseText.company_info});
            }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    // 如果公司名称不为空，执行fetchData()
    handleSubmit(e){
        e.preventDefault();
        const companyName = ReactDOM.findDOMNode(this.refs.companyName).value.trim();
        const companyInfo = ReactDOM.findDOMNode(this.refs.companyInfo).value.trim();
        if(companyName == ''){
            alert("请输入公司名称");
        }else {
            this.UpdateData();
        }
    }

    // 如果提交成功，返回json数据，执行conformUser(responseText)
    UpdateData(){
        fetch("http://121.196.202.247:1010/t_company/?format=json", {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json; charset=utf-8"
            },
            body: JSON.stringify({
                user_id: this.state.loginID,
                company_name: this.state.companyName,
                company_info: this.state.companyInfo,
                company_img: this.state.uploadedFileCloudinaryUrl
            })
        }) .then((response) => response.json())
            .then((responseText) => {
                console.log(responseText);
                console.log(JSON.stringify(responseText));
                this.conformUser(responseText);
            }).catch((error) => {alert("连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    // 如果返回的信息知名该HR不是Boss，则弹窗说明没有权限，反正则提交成功，弹窗并显示已提交的数据到表单中
    conformUser(responseText){
        console.log(responseText);
        if(responseText.fail == 'update fail'){
            alert("抱歉，您无权修改您所在的公司信息！");
            this.setState({companyName: responseText.company_name});
            this.setState({companyInfo: responseText.company_info});
        }else{
            alert("提交成功！");
            console.log(responseText.company_name);
            console.log(responseText.company_info);
        }
    }

    handleChange1(e){
        this.setState({companyName: e.target.value});
    }

    handleChange2(e){
        this.setState({companyInfo: e.target.value});
    }


    // 拖拽本地图片到云端
    onImageDrop(files) {
        console.log("33");
        this.setState({
            uploadedFile: files[0]
        });
        console.log("22");
        this.handleImageUpload(files[0]);
    }

    // 提交本地文件返回url
    handleImageUpload(file) {
        console.log("11");
        fetch("http://120.27.214.53/ZhiXin", {
            method: "POST",
            headers: {},
            body: file
        }) .then((response) => response.text())
            .then((responseText) => {
                console.log(responseText);
                this.setState({uploadedFileCloudinaryUrl: responseText});
            }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    // 点击提交执行handleSubmit(e)
    render() {
        return (
            <form ref="companyForm" onSubmit={function (e) {this.handleSubmit(e)}.bind(this)}>
                <p>公司名称：<input type="text" className="me_comp_name" value={this.state.companyName} onChange={this.handleChange1.bind(this)} ref="companyName"/></p><br/>
                <form>
                公司图片：
                    <Dropzone onDrop={this.onImageDrop.bind(this)} multiple={false} accept="image/*"className="change_comp_photo">
                        <p>点击或者拖拽以更换公司图片</p>
                        <div className="comp_photo_img">
                            <img src={this.state.uploadedFileCloudinaryUrl} alt="公司图片"/>
                        </div>
                    </Dropzone>
                </form>
                <br/>
                <div>
                    <p>公司简介：</p>
                    <div className="me_comp_des"><textarea placeholder="请输入公司简介..." value={this.state.companyInfo} onChange={this.handleChange2.bind(this)} ref="companyInfo"/></div><br/>
                </div>
                <input type="submit" value="提交" className="me_comp_commit" />
            </form>
        );
    }
}


 // 个人设置组件
class UserSet extends React.Component {
    constructor() {
        super();
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
        console.log(userSessionStorage);
        this.state={
            currentIndex : 0,
            loginName : userSessionStorage.user_name,
            loginID : userSessionStorage.user_id,
            loginPhone : userSessionStorage.user_phone,
            loginIDCard : userSessionStorage.user_id_card,
            uploadedFile: null,
            uploadedFileCloudinaryUrl: userSessionStorage.user_image
        };
    }

    // 拖拽本地图片到云端
    onImageDrop(files) {
        console.log("33");
        this.setState({
            uploadedFile: files[0]
        });
        console.log("22");
        this.handleImageUpload(files[0]);
    }

    // 提交本地文件返回url
    handleImageUpload(file) {
        console.log(file);
        console.log("11");
        fetch("http://120.27.214.53/ZhiXin", {
            method: "POST",
            headers: {},
            body: file
        }) .then((response) => response.text())
            .then((responseText) => {
                console.log(responseText);
                this.setState({uploadedFileCloudinaryUrl: responseText});
            }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    // 点击按钮提交新头像，提交图片到服务器
    changeImage(){
        if(this.state.uploadedFile == null){
            alert("请从本地选择您要更换的头像！");
        }else{
            fetch("http://121.196.202.247:1010/image_work/?format=json", {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    "Content-Type": "application/json; charset=utf-8"
                },
                body: JSON.stringify({
                    user_id: this.state.loginID,
                    user_image: this.state.uploadedFileCloudinaryUrl
                })
            }) .then((response) => response.json())
                .then((responseText) => {
                    console.log("asd"+responseText);
                    window.sessionStorage.setItem('userStorage',JSON.stringify(responseText));
                    window.localStorage.setItem('userStorage',JSON.stringify(responseText));
                    alert("新头像更换成功！");
                    window.location.reload('/#/home_me_hr');
                }).catch((error) => {alert("连接职信服务器失败，请查看网络连接状态并刷新页面！")});
        }
    }

    render() {
        return (
            <div>
                <p>姓名：&nbsp;&nbsp;{this.state.loginName}</p><br/>
                <p>职信号：&nbsp;&nbsp;{this.state.loginID}<Link to="/home_me_hr_changePwd"><input type="button" value="更改密码" className="me_user_pass_change"/></Link></p><br/>
                <p>身份证：&nbsp;&nbsp;{this.state.loginIDCard}</p><br/>
                <p>手机号：&nbsp;&nbsp;{this.state.loginPhone}<Link to="/home_me_hr_changePhone"><input type="button" value="更换号码" className="me_user_phone_change"/></Link></p><br/>
                <form onSubmit={function (e) {this.handleSubmit(e)}.bind(this)}>
                    照片：
                    <Dropzone onDrop={this.onImageDrop.bind(this)} multiple={false} accept="image/*"className="change_me_photo">
                        <p>点击或者拖拽以更换您的头像</p>
                        <div className="me_photo_img">
                            <img src={this.state.uploadedFileCloudinaryUrl} alt="您的头像"/>
                        </div>
                    </Dropzone>
                </form>
                    <input type="submit" value="提交新头像" className="me_user_photo_commit" onClick={function (e) {this.changeImage()}.bind(this)}/>
            </div>
        );
    }
}

export default React.createClass({
    render() {
        return (
            <div className="me">
                    <TabsControl>
                         <div name="公司设置">
                             <CompSet/>
                         </div>
                        <div name="个人设置">
                            <UserSet/>
                        </div>
                    </TabsControl>
            </div>
        );
    }
})